/*
 * @Author: zhangchaosen
 * @Date: 2024-05-20 09:29:53
 * @LastEditors: zhangchaosen
 * @LastEditTime: 2024-06-17 13:47:33
 * @Description: 路由
 */
import { type RouteRecordRaw, createRouter, createWebHashHistory, createWebHistory } from 'vue-router'

import { publicRoute, errorRouter } from './modules/static'
import { dynamicRoute } from './modules/dynamic'

/** 常驻路由 */
export const constantRoutes: RouteRecordRaw[] = [...publicRoute, ...errorRouter]

/**
 * 动态路由
 * 用来放置有权限 (Roles 属性) 的路由
 * 必须带有 Name 属性
 */
export const asyncRoutes = [...dynamicRoute]

const router = createRouter({
  history:
    import.meta.env.VITE_ROUTER_HISTORY === 'hash'
      ? createWebHashHistory(import.meta.env.VITE_PUBLIC_PATH)
      : createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
  routes: constantRoutes
})

/**
 * 递归过滤默认路由
 * @param routes
 */
const filterDefaultRoutes = (routes: RouteRecordRaw[]) => {
  const res: string[] = []
  routes.forEach(route => {
    if (route.children) {
      res.push(...filterDefaultRoutes(route.children))
    }
    route.name && res.push(<string>route.name)
  })
  return res
}

/** 重置路由 */
export function resetRouter() {
  // 注意：所有动态路由路由必须带有 Name 属性，否则可能会不能完全重置干净
  try {
    const whiteList = filterDefaultRoutes(constantRoutes)
    router.getRoutes().forEach(route => {
      const { name } = route
      const inWhite = whiteList.includes(name as string)
      if (!inWhite && name) {
        router.removeRoute(name)
      }
    })
  } catch {
    // 强制刷新浏览器也行，只是交互体验不是很好
    window.location.reload()
  }
}

export default router
